
# KNN.py
from numpy import *
import operator

# 用于创建数据


def create_data_set():
    group = array([[0.1, 0.2], [0.2, 0.1], [0.4, 0.5], [0.5, 0.6]])
    labels = ['w1', 'w1', 'w2', 'w2']
    return group, labels


def classify0(in_x, data_set, labels, k):
    data_set_size = data_set.shape[0]  # 获取数组的第一维度的维数，即获取数据量
    diff_mat = tile(in_x, (data_set_size, 1)) - data_set  # 计算距离，首先获取坐标差
    sq_diff_mat = diff_mat**2  # 对坐标差进行分别平方
    sq_distances = sq_diff_mat.sum(axis=1)
    distances = sq_distances**0.5
    sorted_dist_index = distances.argsort()
    class_count = {}  # 创建一个字典

    for i in range(k):
        vote_i_label = labels[sorted_dist_index[i]]
        class_count[vote_i_label] = class_count.get(vote_i_label, 0)+1

    sorted_class_count = sorted(
        class_count.items(), key=operator.itemgetter(1), reverse=True)
    return sorted_class_count[0][0]


groups, labels = create_data_set()
print(groups)
print(labels)
print(classify0((0.1, 0.1), groups, labels, 3))
